from flask import Blueprint, jsonify, render_template, request
from ..database import db
from datetime import datetime

bp = Blueprint('search', __name__, url_prefix='/search')


# a simple page that says hello
@bp.route('/news', methods=['POST', 'GET'])
def search():
    error = None
    news = []
    content=[]
    if request.method == 'POST':
        keywords=request.form['context'].split()
        sql0=" where title like \'%"+keywords[0]+"%\' and title like \'%"+"%\' and title like \'%".join(keywords[1:])+"%\'"
        print(sql0)
        db.reflect()
        tables = db.metadata.tables
        cards_info = [x._asdict() for x in db.session.query(tables["cards"]).all()]
        for info in cards_info:
            name = info['name']
            sql1 = "select * from "+name+sql0
            items = db.session.execute(sql1)
            for i in items:
                test = {'title': i[0], 'url': i[1], 'time': i[2]}
                content.append(test)
        news.append({'content': content})
        return jsonify({'news': news})
    return render_template('search.html', error=error)
    
